首页 > 试题广场 >

去除重复字母

[编程题]去除重复字母
  • 热度指数:1325 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个字符串 s ,请你去除字符串中重复的字母(剩下的字符串中每个字符仅出现一次),并在不改变其相对位置的情况下使剩下的字符串字典序最小。

数据范围:字符串长度满足 , 字符串中仅出现小写英文字母
示例1

输入

"abcd"

输出

"abcd"
示例2

输入

"acbcd"

输出

"abcd"
class Solution:
    def removeDuplicateLetters(self , str: str) -> str:
        # write code here
        rindex = {c:i for i,c in enumerate(str)}
        res = ""
        for  i,c in enumerate(str):
            if c not in res:
                while c < res[-1:] and i < rindex[res[-1]]:
                    res = res[:-1]
                res += c
        return res
发表于 2022-06-24 21:54:39 回复(0)